<template>
    <van-nav-bar :title="alertext" safe-area-inset-top @click-left="onClickLeft" left-text="返回" fixed="'true" placeholder
        left-arrow>

    </van-nav-bar>
    <van-notice-bar left-icon="volume-o" text="管理人员单人单月最高可请五天假。" />
    <div>
        <van-popup v-model:show="showPicker" round>
            <van-picker :columns="columns" @cancel="showPicker = false" @confirm="onConfirm" />
        </van-popup>
    </div>
    <div style="margin: 20px;">
        <van-progress :percentage="percentage * 20" />

        <!-- <van-progress :percentage="percentage"></van-progress> -->
        <p>请假天数剩余额度：{{ percentage }}天</p>
    </div>
    <van-form @submit="onSearch">
        <van-cell-group inset>
            <van-field v-model="prjname" name="项目名称" label="项目名称" readonly />
            <van-field v-model="code" readonly type="number" name="code" label="项目编码" />
            <van-field name="checkboxGroup" label="请假人员">
                <template #input>
                    <van-radio-group v-model="checked">
                        <van-radio v-for="(item, index) in checkboxList" :key="index" :name="item.name"
                            checked-color="#ee0a24" @click="handleClick(item)">{{ item.name }}
                            <van-tag v-if="item.worktype === 'G001'" plain type="primary">项目经理</van-tag>
                            <van-tag v-if="item.worktype === 'G014'" plain type="success">总监理工程师</van-tag>
                        </van-radio>
                    </van-radio-group>
                </template>
            </van-field>
            <van-field v-model="result" is-link readonly name="calendar" label="日历" placeholder="点击选择日期" format="YYYY-mm-dd"
                @click="showCalendar = true"></van-field>
            <van-calendar type="multiple" color="#ee0a24" :min-date="minDate" :max-date="maxDate" :max-range="percentage"
                :show="showCalendar" @confirm="onConfirm"  @close="calendarclose" @open="calendaropen"/>
        </van-cell-group>
        <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
                提交
            </van-button>
        </div>
    </van-form>
</template>


<script>
// 1. 引入你需要的组件
import { Form, Field, CellGroup, Picker, Popup, showToast, RadioGroup, Radio, Button, showDialog, NavBar, Checkbox, CheckboxGroup, Tag, NoticeBar, Calendar, Progress } from 'vant';
// 2. 引入组件样式
import 'vant/lib/index.css';
import { ref } from 'vue';
import axios from "axios";



export default {
    setup() {
        const onClickLeft = () => history.back();
        const columns = [];
        const oldcolumns = [];
        const prjname = ref('');
        const code = ref('');
        const username = ref('');
        const wqzsp = ref('');
        const showPicker = ref(false);
        const checked = ref('');
        const checkboxList = [];
        const formattedDate = ref([]);
        // const result = ref('');
        // const showCalendar = ref(false);
        // const onConfirm = (date) => { 
        //     console.log(typeof(date))
        //     for (let dateinfo of date) {
        //     let year = dateinfo.getFullYear();
        //     let month = ("0" + (dateinfo.getMonth() + 1)).slice(-2);
        //     let day = ("0" + dateinfo.getDate()).slice(-2);
        //     this.list.push(year + "-" + month + "-" + day);
        //     // console.log(formattedDate.value);
        //     }

        //     result.value = `选择了 ${date.length} 个日期`;
        //     showCalendar.value = false;
        // };
        return {
            columns,
            code,
            username,
            formattedDate,
            wqzsp,
            oldcolumns,
            prjname,
            showPicker,
            onClickLeft,
            checked,
            checkboxList,
            // result,
            // onConfirm,
            // showCalendar
        }
    },
    data() {
        return {
            keyword: '',
            selectedValue: '',
            percentage: 0, // 剩余额度初始值，可以根据实际情况设置  
            oldpercentage:0,
            minDate: new Date(),
            maxDate: new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0),
            // formattedDate:[]
            list: [],
            showCalendar: false,
            result: '',
            kqsqlist: [],
            idcardnum: '',
            worktype: ''
        };
    },
    mounted() {
        axios.post('http://bs.bzjsgl.cn/wxapi/Messagetemplate/subjectListInfobycode', {
            code: sessionStorage.getItem('code'),
            openid: sessionStorage.getItem('openid'),
        })
            .then(res => {
                console.log(this.percentage)
                this.prjname = res.data.data['name']
                this.code = res.data.data['code']
                this.checkboxList = res.data.data['list']
                this.percentage = 5 - res.data.data['list'][0]['count']
                this.oldpercentage=this.percentage
                this.idcardnum = res.data.data['list'][0]['num']
                this.worktype = res.data.data['list'][0]['worktype']
                // this.kqlist = res.data.data['list'][0]['kqlist']
                this.kqsqlist = res.data.data['list'][0]['kqlist'].map(obj => obj.kqtime);
                console.log('++++++++++++++++', this.kqsqlist)
                if(this.percentage <= 0){
            showDialog({
                    message: '您的请假额度已用完，请下个月再申请',
                    theme: 'round-button',
                }).then(() => {
                    history.back()
                    // location.reload()
                });
        }
            })
            .catch(function (error) { // 请求失败处理
                console.log(error)
            })
        
    },
    methods: {
        calendarclose(){
            this.showCalendar = false;
        },
        calendaropen(){
            this.percentage=this.oldpercentage
        },
        isBeforeHalfPastEleven() {
            const now = new Date();
            const halfPastEleven = new Date();
            halfPastEleven.setHours(11, 30, 0, 0); // 设置时间为11点半  

            if (!(now.getTime() < halfPastEleven.getTime())) {
                showDialog({
                    message: '申请当天考勤截止时间为11点30分,超过时间只能申请其他日期',
                    theme: 'round-button',
                }).then(() => {
                    location.reload()
                    return false;
                });
            }else{
                console.log(4444444444)
            }
        },
        onSearch() {
            console.log('搜索关键词：', this.prjname, this.code, this.checked.length, '+++++++++',this.list);
            if(this.checked.length ===0){
            showDialog({
                        message: '请选择请假人员',
                        theme: 'round-button',
                    }).then(() => {
                        return false
                    });
           }else if(this.list.length === 0){
            showDialog({
                        message: '请选择请假时间',
                        theme: 'round-button',
                    }).then(() => {
                        return false
                    });
           }else{
            axios.post('http://bs.bzjsgl.cn/wxapi/Messagetemplate/add_glry_shouquan', {
                code: this.code,
                username: this.checked,
                idcardnum: this.idcardnum,
                kqdate: this.list,
                worktype: this.worktype,
                openid: sessionStorage.getItem('openid'),
            })
                .then(res => {
                    showDialog({
                        message: res.data['msg'],
                        theme: 'round-button',
                    }).then(() => {
                        history.back()
                    });
                })
                .catch(function (error) { // 请求失败处理
                    console.log(error)
                })
            }
        },
        handleClick(item) {
            console.log('You clicked on item:', item);
            // 在这里你可以添加你的逻辑代码  
        },
        isToday(dateString) {
            const now = new Date();
            const inputDate = new Date(dateString);

            return inputDate.toDateString() === now.toDateString();
        },
        onConfirm(date) {
            console.log('++++++++++++++++++', date)
            for (let dateinfo of date) {
                let year = dateinfo.getFullYear();
                let month = ("0" + (dateinfo.getMonth() + 1)).slice(-2);
                let day = ("0" + dateinfo.getDate()).slice(-2);
                let xzdate = year + "-" + month + "-" + day;
                if(this.isToday(xzdate)){
                    this.isBeforeHalfPastEleven();
                }
                console.log(xzdate, this.kqsqlist.includes(xzdate))
                if (this.kqsqlist.includes(xzdate)) {
                    showDialog({
                        message: '此' + xzdate + '已经申请过，请重新申请',
                        theme: 'round-button',
                    }).then(() => {
                        location.reload()
                        return false;
                    });
                } else {
                    this.list.push(year + "-" + month + "-" + day);
                    // console.log(formattedDate.value);
                }
            }
            this.showCalendar = false;
            this.percentage = this.percentage - date.length
            this.result = `选择了 ${date.length} 个日期`;
        },
    },
    components: {
        [Form.name]: Form,
        [Field.name]: Field,
        [CellGroup.name]: CellGroup,
        [Picker.name]: Picker,
        [Popup.name]: Popup,
        [showToast.name]: showToast,
        [RadioGroup.name]: RadioGroup,
        [Radio.name]: Radio,
        [Button.name]: Button,
        [showDialog.name]: showDialog,
        [NavBar.name]: NavBar,
        [Checkbox.name]: Checkbox,
        [CheckboxGroup.name]: CheckboxGroup,
        [Tag.name]: Tag,
        [NoticeBar.name]: NoticeBar,
        [Calendar.name]: Calendar,
        [Progress.name]: Progress
    }
}
</script>
